package com.syq.day1;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ThreadLocalRandom;

public class Sample3 {

    interface Lambda extends Serializable {
        int calculate(int a, int b);
    }

    static class Server{
        public static void main(String[] args) throws IOException {
            ServerSocket socket = new ServerSocket(8080);
            System.out.println("server start");
            while (true){
                Socket s = socket.accept();// 客户端链接
                Thread t = new Thread(()->{
                    try {
                        ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
                        Lambda lambda = (Lambda) ois.readObject();
                        int a = ThreadLocalRandom.current().nextInt(10);// 10以内的随机数
                        int b = ThreadLocalRandom.current().nextInt(10);// 10以内的随机数
                        int res = lambda.calculate(a, b);
                        // "%s %d op %d = %d%n"是一个 format   println不识别  %n是换行
                        System.out.printf("%s %d op %d = %d%n", s.getRemoteSocketAddress(), a, b, res);
                    } catch (IOException | ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                });
                t.start();
            }
        }
    }

    static class Client{
        public static void main(String[] args) throws IOException {
            Socket s = new Socket("localhost", 8080);
            System.out.println("client start");
            Lambda lambda = (a, b)->a+b;
            ObjectOutputStream os = new ObjectOutputStream(s.getOutputStream());
            os.writeObject(lambda);
            os.flush();// os输出后 server端通过 readObject读到传递过去的lambda对象
        }
    }

}
